﻿using System;
using System.Linq;
using Biz.EF.Platform.Gxt;
using Hjt212Parser;
using log4net;

namespace Biz.Process
{
    /// <summary>
    /// 主要处理离线、在线
    /// </summary>
    public class ProcessorStatus
    {
        private static ILog Log = LogManager.GetLogger(typeof(ProcessorStatus));
        /// <summary>
        /// 离线指令处理
        /// 注意：方法内已保存
        /// 是否不要保存以提高效率，让外部调用程序保存 
        /// </summary>
        /// <param name="pCtx"></param>
        /// <param name="content"></param>
        public static void Process0000(PlatformGxtContext pCtx, string content)
        {
            try
            {
                var mn = Parser.GetStringByKey("MN", content);
                var datatime = Parser.GetDateTimeByDataTimeThenQnThenNow(content);
                if (!string.IsNullOrEmpty(mn))
                {
                    var items = pCtx.gateway_enterprise_info.Where(t => t.MN.Equals(mn));
                    foreach (var item in items)
                    {
                        if (item.IsOnline.HasValue && item.IsOnline.Value == false) continue;
                        item.IsOnline = false;
                        item.DataTime = datatime;
                    }
                }
                pCtx.SaveChanges();
            }
            catch (Exception ex)
            {
                Log.Error(ex);
            }

        }
        /// <summary>
        /// 心跳指令处理
        /// 在线处理，其实除掉0000的任何指令都表示在线
        /// 注意：方法内已保存
        /// 是否不要保存以提高效率，让外部调用程序保存 
        /// </summary>
        /// <param name="pCtx"></param>
        /// <param name="content"></param>
        public static void Process9999(PlatformGxtContext pCtx, string content)
        {
            try
            {
                var mn = Parser.GetStringByKey("MN", content);
                var datatime = Parser.GetDateTimeByDataTimeThenQnThenNow(content);
                if (!string.IsNullOrEmpty(mn) && !mn.Equals("83028583206998"))
                {
                    var items = pCtx.gateway_enterprise_info.Where(t => t.MN.Equals(mn));
                    foreach (var item in items)
                    {
                        if (item.IsOnline.HasValue && item.IsOnline.Value) continue;
                        item.IsOnline = true;
                        item.DataTime = datatime;
                    }
                }
                pCtx.SaveChanges();
            }
            catch (Exception ex)
            {
                Log.Error(ex);
            }

        }

    }
}
